package cn.bdqn.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class LoginFilter implements Filter {
    private List<String> whiteList= Arrays.asList(
      "/login.jsp",
      "/",
      "/index.jsp"
    );

    //    过滤器的方法
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        //判断有没有登录过
        HttpServletRequest request= (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) res;
        System.out.println(request.getRequestURI());
        //判断是否异步请求
        if(isAjaxRequest(request) || request.getRequestURI().startsWith(request.getContextPath()+"/javascript")){
            chain.doFilter(req,res);
        }else{
            HttpSession session = request.getSession();
            Object token = session.getAttribute("token");
            //获得请求地址
            String path=request.getServletPath();
            if(null==token){
                if(!whiteList.contains(path)){
                    session.setAttribute("toUrl",path);
                    response.sendRedirect("login.jsp");
                }else {
                    chain.doFilter(req,res);
                }
            }else{
                chain.doFilter(req,res);
            }
        }
    }
    public static boolean isAjaxRequest(HttpServletRequest request)
    {

        String accept = request.getHeader("accept");
        if (accept != null && accept.indexOf("application/json") != -1)
        {
            return true;
        }

        String xRequestedWith = request.getHeader("X-Requested-With");
        if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1)
        {
            return true;
        }

//        String uri = request.getRequestURI();
//        if (StringUtils.inStringIgnoreCase(uri, ".json", ".xml"))
//        {
//            return true;
//        }
//
//        String ajax = request.getParameter("__ajax");
//        if (StringUtils.inStringIgnoreCase(ajax, "json", "xml"))
//        {
//            return true;
//        }

        return false;
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String[] arr={"a","b"};
    }

    @Override
    public void destroy() {
    }

}
